package edu.rit.hvz.android.DataLayer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.net.ParseException;
import android.util.Log;

public class ServerDatabaseConnection {
	
	public static void poplulateDatabase(Context ctx){
		populateSquads(ctx);
		populatePlayers(ctx);
		populateNews(ctx);
		populateMissions(ctx);
	}
	
	public static void populateSquads(Context ctx) {
		String queryResults = executePHPQuery("http://vm444-2.se.rit.edu/GetSquads.php");
		PlayerDBAdapter db = new PlayerDBAdapter(ctx);
		try {
			JSONArray jsonArray = new JSONArray(queryResults);			
			db.open();
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				Long id = jsonObject.getLong("ID");
				String name = jsonObject.getString("Name");
				db.createSquad(id, name);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.close();
		}
	}
	
	public static void populatePlayers(Context ctx) {
		String queryResults = executePHPQuery("http://vm444-2.se.rit.edu/GetPlayers.php");
		PlayerDBAdapter db = new PlayerDBAdapter(ctx);
		try {
			JSONArray jsonArray = new JSONArray(queryResults);			
			db.open();
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				Long id = jsonObject.getLong("ID");
				String name = jsonObject.getString("Name");
				String team = jsonObject.getString("Status");
				Integer count = !jsonObject.isNull("Count") ? jsonObject.getInt("Count") : null;
				Long taggedBy = !jsonObject.isNull("Tagging_Zombie") ? jsonObject.getLong("Tagging_Zombie") : null;
				Long squad = !jsonObject.isNull("SquadID") ? jsonObject.getLong("SquadID") : null;
				
				db.createPlayer(id, name, count, team, taggedBy, squad);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.close();
		}
	}

	public static void populateNews(Context ctx) {
		String queryResults = executePHPQuery("http://vm444-2.se.rit.edu/GetNews.php");
		NewsDBAdapter db = new NewsDBAdapter(ctx);
		try {
			JSONArray jsonArray = new JSONArray(queryResults);			
			db.open();
			db.deleteAll();
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				Long id = jsonObject.getLong("PK");
				String title = jsonObject.getString("Title");
				String content = jsonObject.getString("Content");
				boolean visible = jsonObject.getInt("Visability") != 0;
				db.createNews(id, title, content, visible);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.close();
		}
	}
	
	public static void populateMissions(Context ctx) {
		String queryResults = executePHPQuery("http://vm444-2.se.rit.edu/GetMissions.php");
		MissionDBAdapter db = new MissionDBAdapter(ctx);
		try {
			JSONArray jsonArray = new JSONArray(queryResults);			
			db.open();
			db.deleteAll();
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				Long id = jsonObject.getLong("PK");
				String title = jsonObject.getString("Title");
				String content = jsonObject.getString("Content");
				boolean visible = jsonObject.getInt("Visable") != 0;
				db.createMission(id, title, content, visible);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.close();
		}
	}
	
	public static String executePHPQuery(String scriptAddress) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(scriptAddress);
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				// Report error
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return builder.toString();
	}	
	
	public static String executePHPPost(String scriptAddress, List<NameValuePair> data) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpPost post= new HttpPost(scriptAddress);

		try {
			post.setEntity(new UrlEncodedFormEntity(data));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			HttpResponse response = client.execute(post);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return builder.toString();
	}
	
	
}
